package cn.icatw.wallpaperapi.controller;

import cn.icatw.wallpaperapi.common.R;
import cn.icatw.wallpaperapi.common.exception.CustomException;
import cn.icatw.wallpaperapi.domain.Image;
import cn.icatw.wallpaperapi.domain.dto.ImageDto;
import cn.icatw.wallpaperapi.domain.vo.ImageVo;
import cn.icatw.wallpaperapi.service.ImageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * @author icatw
 * @date 2022/10/16
 * @email 762188827@qq.com
 * @apiNote
 */
@Api(tags = "前台图片接口")
@RestController
@RequestMapping("/api/image")
public class FrontImageController {
    @Resource
    ImageService imageService;

    /**
     * 分页查询所有数据
     */
    @ApiOperation(value = "分页查询所有数据 壁纸表（带条件和分页）")
    @GetMapping("/pageList")
    public R page(@RequestParam(required = false) String name,
                  @RequestParam(defaultValue = "1") int current,
                  @RequestParam(defaultValue = "10") int size,
                  ImageDto imageDto,
                  HttpServletRequest request) {
        //if (imageDto != null) {
        Page<ImageVo> result = imageService.pageList(name, current, size, request, imageDto);
        //}
//new Page<ImageVo>()
//        imageService.page(new QueryWrapper<Image>()
//                .eq())
        return R.ok(result);
    }

    /**
     * 模糊搜索
     */
    @ApiOperation(value = "分页模糊查询")
    @GetMapping("/getByName")
    public R getByName(@RequestParam(required = false) String name,
                  @RequestParam(defaultValue = "1") int current,
                  @RequestParam(defaultValue = "10") int size,
                  HttpServletRequest request) {
        Page<ImageVo> result = imageService.getByName(name, current, size, request);
        return R.ok(result);
    }

    @ApiOperation(value = "获取最新壁纸/壁纸排序")
    @GetMapping("/getNew")
    public R getNew(@RequestParam int current, @RequestParam int size) {
        Page<Image> page = new Page<>(current, size);
        return R.ok(imageService.page(page,
                new QueryWrapper<Image>().orderByDesc("create_time", "update_time")));
    }

    //
    //@ApiOperation(value = "根据分类id获取壁纸")
    //@GetMapping("/getByType/{typeId}")
    //public R getByType(@PathVariable int typeId, @RequestParam int current, @RequestParam int size) {
    //    Page<Image> page = new Page<>(current, size);
    //    QueryWrapper<Image> wrapper = new QueryWrapper<Image>().eq("type_id", typeId);
    //    return R.ok(imageService.page(page, wrapper));
    //}
    //
    //@ApiOperation(value = "获取最热壁纸/降序")
    //@GetMapping("/getHot")
    //public R getHot(@RequestParam int current, @RequestParam int size) {
    //    Page<Image> page = new Page<>(current, size);
    //    return R.ok(imageService.page(page
    //            , new QueryWrapper<Image>().orderByDesc("downloads")));
    //}

    @ApiOperation(value = "下载图片", produces = "application/octet-stream")
    @GetMapping(value = "/download/{id}", produces = "application/octet-stream")
    public void download(HttpServletResponse response, @PathVariable String id) {
        ServletOutputStream out = null;
        InputStream inputStream = null;
        Image image = imageService.getById(id);
        try {
            //文件名
            String pdfName = "壁纸.jpg";
            // 获取外部文件流
            URL url = new URL(image.getImageUrl());
            image.setDownloads(image.getDownloads() + 1);
            imageService.updateById(image);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream = conn.getInputStream();
            /**
             * 输出文件到浏览器
             */
            int len = 0;
            // 输出 下载的响应头，如果下载的文件是中文名，文件名需要经过url编码
            //response.setContentType("application/x-download");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(pdfName, "UTF-8"));
            response.setHeader("Cache-Control", "no-cache");
            out = response.getOutputStream();
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(401, "壁纸下载失败！");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception ignored) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (Exception ignored) {
                }
            }
        }
    }
}
